#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Author    : jltxseo
# @File      : views.py
# @Time      : 18年3月19日 上午12:50
# @Software  : PyCharm
from . import base_blueprint
from uuid import uuid4
from flask import redirect, url_for, render_template, flash
from .forms import LoginForm, RegisterForm
from .models import User
from app.database import db


@base_blueprint.route('/')
def index():
    """开始进入首页"""
    return redirect(url_for('blog_blueprint.home'))


@base_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    """View function for login."""

    # Will be check the account whether rigjt.
    form = LoginForm()

    if form.validate_on_submit():
        flash("You have been logged in.", category="success")
        return redirect(url_for('blog_blueprint.home'))

    return render_template('login.html', form=form)


@base_blueprint.route('/logout', methods=['GET', 'POST'])
def logout():
    """View function for logout."""

    flash("You have been logged out.", category="success")
    return redirect(url_for('blog_blueprint.home'))


@base_blueprint.route('/register', methods=['GET', 'POST'])
def register():
    """View function for Register."""

    # Will be check the username whether exist.
    form = RegisterForm()

    if form.validate_on_submit():
        new_user = User(id=str(uuid4()), username=form.username.data, password=form.password.data)
        # 保存新用户
        db.session.add(new_user)
        db.session.commit()
        flash(
            'Your user has been created, please login.',
            category="success")
        return redirect(url_for('base_blueprint.login'))

    return render_template('register.html', form=form)


# erro---------------------------
@base_blueprint.route('/page_<error>')
def route_errors(error):
    """手动抛出错误处理"""
    return render_template('page_{}.html'.format(error))


@base_blueprint.app_errorhandler(404)
def page_not_found(error):
    """所有蓝本触发的异常 View function for user page not found"""
    return render_template('page_404.html'), 404


@base_blueprint.app_errorhandler(403)
def access_forbidden(error):
    """所有蓝本触发的异常"""
    return render_template('page_403.html'), 403


@base_blueprint.app_errorhandler(404)
def not_found_error(error):
    """所有蓝本触发的异常"""
    return render_template('page_404.html'), 404


@base_blueprint.app_errorhandler(500)
def internal_error(error):
    """所有蓝本触发的异常"""
    return render_template('page_500.html'), 500

# ---------------------------erro
